package com.sbhotel.chotellauncher.widget;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.sbhotel.chotellauncher.constant.Constants;

/**
 * @author leihuiming
 * @Description 横向滚动RecyclerView
 */
public class HorizontalRecyclerView extends RecyclerView {

    int mLastFocusPosition = 0;

    public HorizontalRecyclerView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        this.setFocusable(true);
    }

    public HorizontalRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public HorizontalRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void smoothScrollBy(int dx, int dy) {
        if (dx > 0) {
            super.scrollBy(dx + 100, dy);
        } else if (dx < 0) {
            super.scrollBy(dx - 100, dy);
        } else {
            super.scrollBy(dx, dy);
        }
    }

    @Override
    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
        View lastFocusedView = getLayoutManager().findViewByPosition(mLastFocusPosition);
        if(lastFocusedView != null) {
            lastFocusedView.requestFocus();
            return false;
        } else {
            return super.requestFocus(direction, previouslyFocusedRect);
        }
    }

    @Override
    public void requestChildFocus(View child, View focused) {
        super.requestChildFocus(child, focused);
        if (null != child) {
            //取得获得焦点的item的position
            mLastFocusPosition = getChildViewHolder(child).getAdapterPosition();
            Log.d(Constants.LOG_TAG, "requestChildFocus:" + child.getId());
        }
    }

    interface OnChildFocusListener{
        void onChildFoucusChange();
    }
}
